const http = require("http");
const fs = require("fs");
const qs = require("querystring");
const url = require("url");
http.createServer((req, res) => {
    const pn = url.parse(req.url).pathname;
    if (pn.includes("/api")) {
        dataHandle(req, res);
    } else {
        staticHandle(req, res);
    }
}).listen(3000,() => {
    console.log("服务器开启成功:http://localhost:3000");
});

function staticHandle(req, res) {
    const pn = url.parse(req.url).pathname
    fs.readFile("./www" + pn, (err, data) => {
        if (err) {
            res.write("Forbidden \n You don't have permission to access this resource.");
        } else {
            res.write(data);
        }
        res.end();
    });
}

function dataHandle(req, res) {
    if (req.method === "GET") {
        const obj = url.parse(req.url, true).query;
        programHandle(req, res, obj);
    } else if (req.method === "POST") {
        let str = "";
        req.on("data", d => {
            str += d;
        })
        req.on("end", () => {
            const obj = qs.parse(str);
            programHandle(req, res, obj);
        });
    }
}
function programHandle(req,res,data){
    // 功能路由
    // 接收到数据之后，根据数据中携带的功能类型，决定执行那个具体的功能
    switch(data.type){
        case "getBanner":
            getBanner(req,res,data);
            break;
        case "getBanner2":
            getBanner2(req,res,data);
            break;
        case "login":
            login(req,res,data);
            break;
        case "register":
            register(req,res,data);
            break;
        case "jsonp":
            jsonp(req,res,data);
            break;
        case "getGoods":
            getGoods(req,res,data);
            break;
        default:
            error(req,res,data);
    }
}
function jsonp(req,res,data){
    const msg = {
        title:"这是后端接收到的前端的数据，再还给你",
        data:data
    }


    res.write(data.cb + "('"+ JSON.stringify(msg) +"')");
    res.end();
}
// function jsonp(req,res,data){
//     const msg = {
//         title:"这是后端接收到的前端的数据，再还给你",
//         data:data
//     }
//     res.write("fn('"+ JSON.stringify(msg) +"')");
//     res.end();
// }

function register(req, res, reqData){
    fs.readFile("./database/users.json","utf-8",(err, data)=>{
        const userMsg = err ? [] : (data ? JSON.parse(data) : []);
        const obj = {};
        if(userMsg.some(val=>val.username === reqData.username)){
            obj.code = 0;
            obj.title = "注册失败，用户名重复";
            obj.data = "NOTDATA"
            res.write(JSON.stringify(obj));
            res.end();
        }else{
            userMsg.push({
                username:reqData.username,
                password:reqData.password
            })
            fs.writeFile("./database/users.json",JSON.stringify(userMsg),err=>{
                obj.code = 1;
                obj.title = "注册成功";
                obj.data = "NOTDATA";
                res.write(JSON.stringify(obj));
                res.end();
            })
        }
    })
}
function login(req,res,reqData){
    fs.readFile("./database/users.json","utf-8",(err, data)=>{
        const userMsg = err ? [] : (data ? JSON.parse(data) : []);
        const obj = {};
        let i = 0;
        const flag = userMsg.some((val,idx)=>{
            i = idx;
            return val.username === reqData.username;
        })
        if(flag){
            if(userMsg[i].password === reqData.password){
                obj.code = 1;
                obj.title = "登陆成功";
                obj.data = userMsg[i].username;
            }else{
                obj.code = 2;
                obj.title = "登陆失败，密码错误";
                obj.data = "NOTDATA";
            }
        }else{
            obj.code = 0;
            obj.title = "登陆失败，用户名不存在";
            obj.data = "NOTDATA"
        }
        res.write(JSON.stringify(obj));
        res.end();
    })
}






function getBanner(req,res,data){
    // 服务器先读取banner数据
    fs.readFile("./database/banner.json","utf-8",(err,data)=>{
        const obj = {}
        if(err){
            obj.code = 0;
            obj.title = "数据查找失败";
            obj.data = [];
        }else{
            obj.code = 1;
            obj.title = "数据查找成功";
            obj.data = JSON.parse(data);
        }
        res.write(JSON.stringify(obj))
        res.end()
    })
}

function getGoods(req,res,data){
    // 服务器先读取banner数据
    fs.readFile("./database/product.json","utf-8",(err,data)=>{
        const obj = {}
        if(err){
            obj.code = 0;
            obj.title = "数据查找失败";
            obj.data = [];
        }else{
            obj.code = 1;
            obj.title = "数据查找成功";
            obj.data = JSON.parse(data);
        }
        res.write(JSON.stringify(obj))
        res.end()
    })
}


function getBanner2(req,res,data){
    // 服务器先读取banner数据
    fs.readFile("./database/banner2.json","utf-8",(err,data)=>{
        const obj = {}
        if(err){
            obj.code = 0;
            obj.title = "数据查找失败";
            obj.data = [];
        }else{
            obj.code = 1;
            obj.title = "数据查找成功";
            obj.data = JSON.parse(data);
        }
        res.write(JSON.stringify(obj))
        res.end()
    })
}

function error(req,res,data){
    res.write("Forbidden \n You don't have permission to access this resource.");
    res.end();
}